import JSEncrypt from 'jsencrypt'
import * as CryptoJS from 'crypto-js'
import storage from '@/utils/storage'
import { appInfo, ddmgConfig } from '@/utils/appConfig'
// import store from '@/store/index'
import { EncodeBase64, EncryptCaller, DecryptCaller } from '@/utils/encryption'
import { getMenuID } from '@/utils/index'
import { Message } from 'element-ui'
import store from '@/store/index.js';


const publicEncrypt = (publicKey, value) => {
  const jsencrypt = new JSEncrypt()
  jsencrypt.setPublicKey(publicKey)
  let text = jsencrypt.encrypt(value)
  text = btoa(atob(text).padStart(128, '\0'))
  return text
}
// 清除字符串尾部空格
const trimData = data => {
  if (typeof data === 'string') {
    return data.trim()
  } else if (Array.isArray(data)) {
    return data.map(it => trimData(it))
  } else if (Object.prototype.toString.call(data) === '[object Object]') {
    return Object.keys(data).reduce(
      (c, n) => ({ ...c, [n]: trimData(data[n]) }),
      {}
    )
  }
  return data
}
const MD5 = value => CryptoJS.MD5(value).toString()

const getEventid = () =>
  Math.floor(Math.random() * (99999999 - 10000000) + 10000000)

// 获取载荷
export const getPayload = (callmethod, data = '') => {
  const clientid = storage.getStorage('fingerprint')
  // console.log(ddmgConfig)
  // 传输凭据被清空
  if (!clientid) {
    if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
      const getEventid = () => Math.floor(Math.random() * (99999999 - 10000000) + 10000000);
      storage.setStorage('fingerprint',getEventid())
    } else {
      Message({
        showClose: true,
        message: '本地指纹凭据信息已被清空',
        type: 'error',
        onClose: ()=>{
          window.location.reload()
        }
      });
    }
  }
  try {
    const timestamp = new Date().getTime()
    const reqBody = {
      timestamp,
      callmethod,
      version: 1,
      isdebug: 1,
      clientid,
      data: trimData(data)
    }
    var reqJson = {
      ...appInfo,
      _host: ddmgConfig.host,
      _caller: ddmgConfig.caller,
      _callmethod: callmethod,
      _timestamp: timestamp,
      _eventid: getEventid(),
      _data: EncryptCaller(reqBody, ddmgConfig.callee)
    }
    // console.log('getPayload', reqJson, reqBody);
    return {
      callmethod,
      data: reqJson
    }
  } catch (error) {
    console.log('getPayload-catch =>', error)
  }
}

// 获取登录载荷
export const getLoginPayload = (callmethod, data = {}, needMenuId = true) => {
  // 若有传menuId 则以传入的menuId为准；没有传menuId则统一处理；
  data.SystemID = storage.getStorage('currentSystemID') || "8000"
  const menuId = getMenuID()

  if (Array.isArray(data)) {
    if (needMenuId) {
      data = {
        globalArray: data,
        globalMenuId: menuId
      }
    }
  } else {
    if (!data.globalMenuId && needMenuId) data.globalMenuId = menuId
  }
  // 非线上环境打印请求参数信息
  const kkunUid = storage.getStorage('kkun_uid')
  const clientid = storage.getStorage('fingerprint')
  const rsaPub = DecryptCaller(
    storage.getStorage('rsa_pub') || '',
    ddmgConfig.callee
  )
  console.log(`请求接口${callmethod},请求加密前参数${JSON.stringify(data)}`)
  if (!clientid) {
    if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
      const getEventid = () => Math.floor(Math.random() * (99999999 - 10000000) + 10000000);
      storage.setStorage('fingerprint',getEventid())
    }else{
      Message({
        showClose: true,
        message: '本地指纹凭据信息已被清空',
        type: 'error',
        onClose: ()=>{
          window.location.reload()
        }
      });
    }
    return
  }
  console.log('rsaPub:', rsaPub, 'storage:', storage.getStorage('rsa_pub'), 'ddmgConfig:', ddmgConfig.callee,(!kkunUid || !clientid || !rsaPub))
  // 传输凭据被清空
  if (!kkunUid || !clientid || !rsaPub) {
    Message({
      showClose: true,
      message: '本地指纹凭据信息已被清空',
      type: 'error',
      onClose: ()=>{
        store.dispatch('admin/account/logout')
      }
    });
    return
  }
  try {
    const timestamp = new Date().getTime()
    const uid = DecryptCaller(kkunUid || '', ddmgConfig.callee)
    const params = {
      _caller: ddmgConfig.caller,
      _callmethod: callmethod,
      _eventid: getEventid(),
      _timestamp: timestamp,
      _host: ddmgConfig.host
    }
    const reqBody = {
      timestamp,
      callmethod,
      version: 1,
      isdebug: 1,
      clientid,
      data: trimData(data),
      uid
    }
    const loginkey = {
      uid,
      ...params
    }
    const encryptionData = EncryptCaller(reqBody, ddmgConfig.callee)
    const joinLoginkey = Object.values(loginkey).join(',')
    const md5Data = MD5(encryptionData)
    const md5Loginkey = MD5(joinLoginkey)
    const joinMd5 = md5Data + ',' + md5Loginkey
    const rsaData = publicEncrypt(rsaPub, joinMd5)
    const base64Data = EncodeBase64(rsaData)
    var reqJson = {
      ...params,
      ...appInfo,
      _loginkey: base64Data,
      _data: encryptionData
    }
    if (!rsaData || base64Data.length < 15) {
      Message({
        showClose: true,
        message: '_loginkey加密不正确',
        type: 'error',
      });
    }
    console.log('getLoginPayload', reqJson, reqBody);

    return {
      callmethod,
      data: reqJson
    }
  } catch (error) {
    Message({
      showClose: true,
      message: '本地指纹凭据信息已被清空',
      type: 'error',
      onClose: ()=>{
        store.dispatch('admin/account/logout')
      }
    });
    console.log('getLoginPayload-catch =>', error)
  }
}
